package com.zzy.filter;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.sql.*;

/**
 * 使用 byte[] 读取 数据库 使用 blob 存
 */
public class TypeHanderBlobByte extends BaseTypeHandler<byte[]> {


    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, byte[] bytes, JdbcType jdbcType) throws SQLException {
        ByteArrayInputStream bis = null;
        try {
            bis = new ByteArrayInputStream(bytes);
        } catch (Exception e) {
            throw new RuntimeException("bytes Error!");
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    throw new RuntimeException("bytes Error!");
                }
            }
        }
        preparedStatement.setBinaryStream(i, bis);
    }

    @Override
    public byte[] getNullableResult(ResultSet resultSet, String s) throws SQLException {
        Blob blob =  resultSet.getBlob(s);
        if(blob==null){
            return null;
        }
        byte[] bytes = blob.getBytes((long)1, (int)blob.length());
        return bytes;
    }

    @Override
    public byte[] getNullableResult(ResultSet resultSet, int i) throws SQLException {
        Blob blob =  resultSet.getBlob(i);
        if(blob==null){
            return null;
        }
        byte[] bytes = blob.getBytes((long)1, (int)blob.length());
        return bytes;
    }

    @Override
    public byte[] getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        Blob blob = callableStatement.getBlob(i);
        if(blob==null){
            return null;
        }
        byte[] bytes = blob.getBytes((long)1, (int)blob.length());
        return bytes;
    }
}
